package com.lindroy.androidplayer.ui.search

import android.view.Menu
import android.widget.ImageView
import androidx.activity.viewModels
import androidx.appcompat.widget.SearchView
import androidx.core.view.isVisible
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.google.android.flexbox.*
import com.google.android.material.chip.Chip
import com.lindroy.androidplayer.R
import com.lindroy.androidplayer.base.BaseActivity
import com.lindroy.androidplayer.constants.SP_KEY_SEARCH_HISTORY
import com.lindroy.androidplayer.extensions.*
import com.lindroy.androidplayer.logic.model.SearchHotKeyworkResp
import com.lindroy.androidplayer.viewmodel.SearchViewModel
import com.lindroy.lib_utils.extensions.*
import com.orhanobut.logger.Logger
import com.youngfeng.snake.annotations.EnableDragToClose
import kotlinx.android.synthetic.main.activity_search.*

/**
 * @author Lin
 * @date 2021/4/30
 * @function 搜索页面
 * @Description
 */

private const val SEPERATOR = "-"
@EnableDragToClose
class SearchActivity(override val layoutId: Int = R.layout.activity_search) : BaseActivity() {

    private val searchViewModel: SearchViewModel by viewModels()

    private val hotKeyAdapter by lazy {
        BaseSimpleAdapter<SearchHotKeyworkResp>(R.layout.search_keyword_item) { holder, item ->
            holder.getView<Chip>(R.id.chipName).apply {
                text = item.name
                setOnClickListener {
                    toSearchPage(item.name)
                }
            }
        }
    }

    private val historyAdapter by lazy {
        object : BaseQuickAdapter<String, BaseViewHolder>(R.layout.search_history_item) {
            override fun convert(holder: BaseViewHolder, item: String) {
                holder.setText(R.id.tvKeyword, item)
                holder.getView<ImageView>(R.id.ivClear).setOnClickListener {
                    remove(item)
                    saveHistory()
                    setHistoryState(data)
                }
            }

        }
    }

    override fun initView() {
        initToolBar("")
        rvHotKey.layoutManager = FlexboxLayoutManager(mContext).apply {
            flexWrap = FlexWrap.WRAP
            flexDirection = FlexDirection.ROW
            justifyContent = JustifyContent.FLEX_START
            alignItems = AlignItems.CENTER
        }
        rvHotKey.adapter = hotKeyAdapter
        rvHistory.setLineDivider()
        rvHistory.adapter = historyAdapter

        val history = getSpString(SP_KEY_SEARCH_HISTORY)
        val list = history.isNotEmpty().yes {
            history.split(SEPERATOR)
        }.no { listOf() }
        setHistoryState(list).yes {
            historyAdapter.setList(list)
        }
    }

    override fun initData() {
        searchViewModel.reqSearchKeywords()
    }

    override fun initListener() {
        searchViewModel.searchHotKeywordsState.observe(this) { resultState ->
            parseState(resultState, onLoading = {
                showLoading()
            }, onError = {
                dismissLoading()
                stateLayout.setNetworkErrorLayout()
            }) {
//                stateLayout.showContent()
                hotKeyAdapter.setList(it)
                dismissLoading()
            }
        }
    }

    override fun initClick() {
        ivClearAll.setOnClickListener {
            historyAdapter.data.clear()
            historyAdapter.notifyDataSetChanged()
            setHistoryState(listOf())
            putSpString(SP_KEY_SEARCH_HISTORY, "")
        }
        historyAdapter.setOnItemClickListener { _, view, position ->
            toSearchPage(historyAdapter.data[position])
        }
    }

    /**
     * 根据是否有历史记录来处理界面
     * 返回true表示有
     */
    private fun setHistoryState(list: List<String>): Boolean = list.isNotEmpty().yes {
        rvHistory.setVisible()
        tvNoHistory.setGone()
        ivClearAll.setVisible()
        true
    }.no {
        tvNoHistory.setVisible()
        rvHistory.setGone()
        ivClearAll.setGone()
        false
    }

    private fun saveHistory() {
        putSpString(SP_KEY_SEARCH_HISTORY, historyAdapter.data.joinToString(SEPERATOR))
    }

    private fun toSearchPage(keyword: String) {
        if (tvNoHistory.isVisible) {
            tvNoHistory.setGone()
        }
        if (historyAdapter.data.contains(keyword)) {
            historyAdapter.data.remove(keyword)
        }
        historyAdapter.data.add(keyword)
        historyAdapter.notifyDataSetChanged()
        saveHistory()
        setHistoryState(historyAdapter.data)
        SearchResultActivity.start(mContext, keyword)
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.search_menu, menu)
        val searchView = menu?.findItem(R.id.action_search)?.actionView as SearchView
        searchView.also {
            it.maxWidth = Integer.MAX_VALUE
            it.onActionViewExpanded()
            it.queryHint = getString(R.string.hint_search)
            it.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
                override fun onQueryTextSubmit(query: String?): Boolean {
                    query?.let { it1 -> toSearchPage(it1) }
                    return false
                }

                override fun onQueryTextChange(newText: String?): Boolean {
                    return false
                }

            })
            it.isSubmitButtonEnabled = true
        }
        try {
            val field = searchView.javaClass.getDeclaredField("mGoButton")
            field.isAccessible = true
            val mGoButton = field.get(searchView) as ImageView
            mGoButton.setImageResource(R.drawable.ic_search)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return super.onCreateOptionsMenu(menu)
    }


}